package com.sun.weekend.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.sun.weekend.R;
import com.sun.weekend.adapter.TaskAdapter;
import com.sun.weekend.base.BaseActivity;
import com.sun.weekend.beans.BundleBean;
import com.sun.weekend.beans.TaskBean;
import com.sun.weekend.util.Go2Util;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, XRecyclerView.LoadingListener {

    ImageView user_icon;
    TextView user_name;
    TextView user_email;
    FragmentManager fg;
    XRecyclerView task_list;
    TaskAdapter adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initBaseView();

    }

    private void initBaseView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        user_icon = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.user_icon);
        user_name = (TextView) navigationView.getHeaderView(0).findViewById(R.id.user_name);
        user_email = (TextView) navigationView.getHeaderView(0).findViewById(R.id.user_email);
        task_list = (XRecyclerView) findViewById(R.id.task_list);
        task_list.setLoadingListener(this);
        task_list.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        adapter = new TaskAdapter(this);
        task_list.setAdapter(adapter);
        fg = getSupportFragmentManager();
        user_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userBean != null) {
                    BundleBean bean = new BundleBean();
                    bean.setSign("UserCenter");
                    Go2Util.go2Module(getApplicationContext(),bean);

                }else{
                    login();
                }
                if (drawer.isDrawerOpen(GravityCompat.START)) {

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            drawer.closeDrawer(GravityCompat.START);
                        }
                    },200);
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
       if (userBean != null) {
           task_list.setRefreshing(true);
           user_name.setText(userBean.getUsername());
           user_email.setText(userBean.getEmail());
           if (userBean.getAvstar() != null) {
               Glide.with(this).load(userBean.getAvstar()
                       .getFileUrl())
                       .placeholder(R.mipmap.ic_launcher)
                       .into(user_icon);
           }
       }else{
           user_name.setText("登录");
       }

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            BundleBean bean = new BundleBean();
            bean.setSign("EditTask");
            Go2Util.startDetailActivity(mContext,bean);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_message) {
            // Handle the camera action
            BundleBean bean = new BundleBean();
            bean.setSign("Message");
            Go2Util.go2Module(this,bean);
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void loadData(final boolean isRefresh) {

        BmobQuery<TaskBean> query = new BmobQuery<>();
        query.setLimit(5);
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.order("-createdAt");
        query.setSkip(isRefresh? 0:adapter.getItemCount());
        query.findObjects(new FindListener<TaskBean>() {
            @Override
            public void done(List<TaskBean> list, BmobException e) {

                if (list == null || e != null){
                    task_list.refreshComplete();
                    return;
                }
                if (isRefresh){
                    adapter.clear();
                }
                task_list.setLoadingMoreEnabled(list.size() >= 5);
                adapter.append(list);
                task_list.refreshComplete();
            }
        });
    }

    @Override
    public void onRefresh() {
        loadData(true);
    }

    @Override
    public void onLoadMore() {
        loadData(false);
    }
}
